import { Component, OnInit, Input } from '@angular/core';
import { NzModalSubject } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { UsersService } from '../../services';
import { LocalstoreService } from '../../../shared/services';

@Component({
  selector: 'ege-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.scss']
})
export class ChangePasswordComponent implements OnInit {

  _data: any;

  isConfirmLoading = false;
  validateForm: FormGroup;

  token = this.localstorageService.getItem('USER_TOKEN');

  @Input()
  set user(value: any) {
    this._data = value;
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[ i ].markAsDirty();
      }
    }

    if (this.validateForm.valid) {
      this.isConfirmLoading = true;

      const userId = this._data.id;
      const body = this.validateForm.value;
      // console.log(this._data);

      this.usersService
          .editUser(userId, body, this.token.id)
          .subscribe(result => {
            this.emitDataOutside(result);
            this.subject.next('onOk');

            this.isConfirmLoading = false;
          }, error => {
            this.isConfirmLoading = false;
          });
    }
  }

  updateConfirmValidator() {
    /** wait for refresh value */
    setTimeout(_ => {
      this.validateForm.controls[ 'checkPassword' ].updateValueAndValidity();
    });
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls[ 'password' ].value) {
      return { confirm: true, error: true };
    }
  }

  emitDataOutside(user: any) {
    this.subject.next(user);
  }

  handleCancel(e) {
    this.subject.destroy('onCancel');
  }

  constructor(
    private fb: FormBuilder,
    private subject: NzModalSubject,
    private usersService: UsersService,
    private localstorageService: LocalstoreService,
  ) {
    this.subject.on('onDestory', () => {
      // console.log('destroy');
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      password         : [ null, [ Validators.required ] ],
      checkPassword    : [ null, [ Validators.required, this.confirmationValidator ] ],
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

}
